import React, { useState, useEffect } from 'react';
import { Row, Col, Card, Table, Progress,Drawer,Button,Select} from 'antd';
import ReactECharts from 'echarts-for-react';
import { getDpInfo,getAllDpInfo,getAllBkList,getBkStockList,getDpJJ,getDpTrace,getNewBkList,getBkTrace } from '../../service/apis/monitor';
import { BKJD } from '../../service/config';
import './index.css';
import { color } from 'echarts';

const Monitor: React.FC = () => {
  const [dpInfo, setDpInfo] = useState({
    ztNum: 0,
    dtNum: 0,
    szNum: 0,
    xdNum: 0,
    qd: 0,
    jyr: 0,
    fValue:0,
    vValue:0,
    zqxy: 0,
    zrdbZqxy:0,
    highKpzqxy: 0,
    ztZqxy: 0,
    dbZqxy: 0
  });
  const [lineData, setLineData] = useState([]);
  const [columnData, setColumnData] = useState([]);
  const [marketEmotionData, setMarketEmotionData] = useState({
    kpyj: { dp:0,high: 0, zt: 0, db: 0 }
  });

  const [bidData, setBidData] = useState([]);
  const [traceData, setTraceData] = useState([]);
  const [bkTraceData, setBkTraceData] = useState([]);
  const [bkList, setBkList] = useState([]);
  const [curBkCode, setCurBkCode] = useState(null);
  const getCircleColor = (percent) => {
    const red = Math.min(255, Math.floor((percent / 100) * 255));
    return `rgb(${red}, 0, 0)`;
  };

  useEffect(() => {
    // 模拟获取数据
    getDpInfo().then(data => {
      setDpInfo(data); 
      if (data) {
        console.log(data);
        setMarketEmotionData({
          kpyj: { dp:data.kpYj,high: data.highKpYj, zt: data.ztKpYj, db: data.dbKpYj },
          // zqxy: { dp:data.zqxy,high: data.highZqxy, zt: data.ztZqxy, db: data.dbZqxy},
          // kqxy: { dp:data.kqxy,high: data.highKqxy, zt: data.ztKqxy, db: data.dbKqxy},
        });
      }
      getDpJJ().then(dpJJ => {
        setBidData(dpJJ.map(item => ({ date: item.jyr.toString(), fbValue:Number(item.fbValue)/100000000})));
      });
      getDpTrace().then(traces => {
        setTraceData(traces);
      });

      getNewBkList({jyr:null}).then(bkList => {
        setBkList(bkList.map(item => ({ label: `${item.name}`, value: item.code })));
      }).catch(error => console.error('Error fetching monitor data:', error));

      getAllDpInfo().then(dpInfos => {
        if (!dpInfos) return;
        if(dpInfos[0].jyr != data.jyr){
          dpInfos.unshift(data);
        }
        setLineData(dpInfos.map(item => ({ date: item.jyr.toString(), value: item.qd })));
        setColumnData(dpInfos.map(item => ({ date: item.jyr.toString(), value: Number(item.fValue)/10000000 })));
      });
    });

  }, []);
  const bkSelectChange = (value) => {
    setCurBkCode(value);
    getBkTrace({bkcode:value}).then(traces => {
      setBkTraceData(traces);
    });
  };
  const getCombinedOption = () => ({
    tooltip: {
      trigger: 'axis',
      formatter: (params) => {
        const date = new Date(params[0].axisValue);
        const year = date.getFullYear();
        const month = (date.getMonth() + 1).toString().padStart(2, '0');
        const day = date.getDate().toString().padStart(2, '0');
        const formattedDate = `${year}/${month}/${day}`;
        const marketStrength = params[0].data;
        const profitEffect = (Number(params[1].data)*1000).toFixed(0);
        return `日期: ${formattedDate}<br/>市场强度: ${marketStrength}<br/>成交量: ${profitEffect} 亿`;
      },
    },
    legend: {
      data: ['市场强度', '赚钱效应'],
    },
    xAxis: {
      type: 'category',
      data: lineData.map(item => item.date),
      axisLabel: {
        formatter: (value) => {
          const date = new Date(value);
          const month = (date.getMonth() + 1).toString().padStart(2, '0');
          const day = date.getDate().toString().padStart(2, '0');
          return `${month}/${day}`;
        },
      },
      axisPointer: {
        type: 'shadow',
      },
    },
    yAxis: {
      type: 'value',
      max: 100,
      splitLine: {
        show: true,
        lineStyle: {
          type: 'dashed',
        },
      },
      axisLabel: {
        formatter: '{value}',
      },
      splitArea: {
        show: true,
        areaStyle: {
          color: ['transparent', 'rgba(154, 220, 141, 0.2)', 'transparent'],
        },
      },
    },
    dataZoom: [
      {
        type: 'inside',
        start: 65,
        end: 100,
      },
      {
        start: 65,
        end: 100,
      },
    ],

    series: [
      {
        name: '市场强度',
        type: 'line',
        data: lineData.map(item => item.value),
        lineStyle: {
          color: 'red',
        },
        markPoint: {
          data: [
            {
              coord: [dpInfo.jyr, dpInfo.qd],
              value: dpInfo.qd,
              symbol: 'pin',
              symbolSize: 50,
              label: {
                show: true,
                formatter: `{c}`,
                color: 'white',
              },
              itemStyle: {
                color: 'red',
              },
            },
          ],
        },
      },
      {
        name: '成交量',
        type: 'bar',
        data: columnData.map(item => item.value),
        itemStyle: {
          color: 'green',
        },
        barWidth: '60%',
      },
    ],
  });

  const getMarketEmotionOption = () => ({
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      },
    },
    legend: {
      data: ['大盘', '高位', '涨停', '断板'],
      selectedMode: 'multiple', 
    },
    xAxis: {
      type: 'category',
      data: ['开盘溢价'],
      axisLabel: {
        interval: 0,
        rotate: 0,
      },
    },
    yAxis: {
      type: 'value',
      max: 10,
      min: -10,
      splitLine: {
        show: true,
        lineStyle: {
          type: 'dashed',
        },
      },
      axisLabel: {
        formatter: '{value}',
      },
      splitArea: {
        show: true,
        areaStyle: {
          color: ['transparent', 'rgba(154, 220, 141, 0.2)', 'transparent'],
        },
      },
    },
    series: [
      {
        name: '大盘',
        type: 'bar',
        data: [marketEmotionData.kpyj.dp],
      },
      {
        name: '高位',
        type: 'bar',
        data: [marketEmotionData.kpyj.high],
      },
      {
        name: '涨停',
        type: 'bar',
        data: [marketEmotionData.kpyj.zt],
      },
      {
        name: '断板',
        type: 'bar',
        data: [marketEmotionData.kpyj.db],
      },
    ],
  });

  const getBidOption = () => ({
    tooltip: {
      trigger: 'axis',
      formatter: (params) => {
        const date = new Date(params[0].axisValue);
        const year = date.getFullYear();
        const month = (date.getMonth() + 1).toString().padStart(2, '0');
        const day = date.getDate().toString().padStart(2, '0');
        const formattedDate = `${year}/${month}/${day}`;
        const marketStrength = params[0].data;
        const profitEffect = (Number(params[1].data)*10000).toFixed(0);
        return `日期: ${formattedDate}<br/>竞价资金: ${marketStrength}亿<br/>竞价成交量: ${profitEffect} 万`;
      },
    },
    legend: {
      data: ['竞价金额', '竞价成交金额'],
    },
    xAxis: {
      type: 'category',
      data: bidData.map(item => item.date),
      axisLabel: {
        formatter: (value) => {
          const date = new Date(value);
          const month = (date.getMonth() + 1).toString().padStart(2, '0');
          const day = date.getDate().toString().padStart(2, '0');
          return `${month}/${day}`;
        },
      },
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: '{value} 亿',
      },
    },
    series: [
      {
        name: '竞价金额',
        type: 'line',
        data: bidData.map(item => item.fbValue),
        lineStyle: {
          color: 'blue',
        },
      },

    ],
  });

  // 将 curTime 转换为时间戳
const convertTimeToTimestamp = (time) => {
  const [hours, minutes] = time.split(':');
  return new Date(2025, 1, 27, parseInt(hours), parseInt(minutes)).getTime();
};

const getTraceOption = () => ({
  tooltip: {
    trigger: 'axis',
    formatter: (params) => {
      const date = new Date(params[0].axisValue);
      const time = `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
      return `时间: ${time}<br/>`
        + `开盘赚钱效应: ${params[0].data[1]}<br/>`
        + `昨收赚钱效应: ${params[1].data[1]}<br/>`
        + `亏钱效应: ${params[2].data[1]}`;
    },
  },
  legend: {
    data: ['开盘赚钱效应', '昨收赚钱效应', '亏钱效应'],
    // data: ['开盘赚钱效应', '昨收赚钱效应','亏钱效应','高位开盘赚钱效应', '高位昨收赚钱效应','高位亏钱效应','涨停开盘赚钱效应', '涨停昨收赚钱效应','涨停亏钱效应','断板开盘赚钱效应', '断板昨收赚钱效应','断板亏钱效应'],
  },
  xAxis: {
    type: 'time',
    // min: convertTimeToTimestamp('09:20'), // 设置 x 轴的最小值为 09:00
    max: convertTimeToTimestamp('15:00'), // 设置 x 轴的最大值为 16:00
    axisLabel: {
      showMinLabel: true, // 显示起点刻度
      showMaxLabel: true,
      formatter: (value) => {
        const date = new Date(value);
        return `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
      },
      interval: (index, value) => {
        const date = new Date(value);
        const hours = date.getHours();
        const minutes = date.getMinutes();
        // 过滤掉 11:30 到 13:00 的刻度
        if ((hours === 11 && minutes >= 30) || (hours === 12) || (hours === 13 && minutes === 0)) {
            return false;
        }
        // 每半小时显示一个刻度
        return minutes % 30 === 0;
      },
    },
    xisTick: {
      interval: 30 * 60 * 1000, // 每半小时一个刻度
    },
  },
  yAxis: {
    type: 'value',
  },
  series: [
    {
      name: '昨收赚钱效应',
      type: 'line',
      data: traceData.map(item => [convertTimeToTimestamp(item.curTime), item.zqxy]),
      smooth: true,
      showSymbol: false,
      color: 'red',
      markPoint: {
        data: [
          { type: 'max', name: '最大值' },
        ],
      },
    },
    {
      name: '亏钱效应',
      type: 'line',
      data: traceData.map(item => [convertTimeToTimestamp(item.curTime), item.kqxy]),
      smooth: true,
      showSymbol: false,
      color: 'green',
      markPoint: {
        data: [
          { type: 'min', name: '最小值' },
        ],
      },
    },
  ],
});

  const getBkTraceOption = () => ({
    tooltip: {
      trigger: 'axis',
      formatter: (params) => {
        const date = new Date(params[0].axisValue);
        const time = `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
        return `时间: ${time}<br/>`
          + `开盘赚钱效应: ${params[0].data[1]}<br/>`
          + `昨收赚钱效应: ${params[1].data[1]}<br/>`
          + `亏钱效应: ${params[2].data[1]}`;
      },
    },
    legend: {
      data: ['开盘赚钱效应', '昨收赚钱效应','亏钱效应'],
    },
    xAxis: {
      type: 'time',
      // min: convertTimeToTimestamp('09:20'), // 设置 x 轴的最小值为 09:00
      max: convertTimeToTimestamp('15:00'), // 设置 x 轴的最大值为 16:00
      axisLabel: {
        formatter: (value) => {
          const date = new Date(value);
          return `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
        },
      },
    },
    yAxis: {
      type: 'value',
    },
    series: [
      {
        name: '昨收赚钱效应',
        type: 'line',
        data: bkTraceData.map(item => [convertTimeToTimestamp(item.curTime), item.zqxy]),
        smooth: true,
        showSymbol: false,
        color: 'red',
        markPoint: {
          data: [
            { type: 'max', name: '最大值' },
          ],
        },
      },
      {
        name: '亏钱效应',
        type: 'line',
        data: bkTraceData.map(item => [convertTimeToTimestamp(item.curTime), item.kqxy]),
        smooth: true,
        showSymbol: false,
        color: 'green',
        markPoint: {
          data: [
            { type: 'min', name: '最小值' },
          ],
        },
      },
    ],
  });
  
  return (
    <div>
      <Row gutter={[16, 16]}>
        <Col span={8}>
          <Card title="市场情绪">
          <div style={{ height: '200px', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <div style={{ display: 'flex', width: '100%' }}>
                <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'space-around', alignItems: 'center' }}>
                  <div style={{ width: '100%', display: 'flex', alignItems: 'center' }}>
                    <div>涨停家数</div>
                    <Progress percent={(dpInfo.ztNum / 100) * 100} strokeColor="red" showInfo={false} style={{ flex: 1, marginLeft: '10px' }} />
                    <div style={{ marginLeft: '10px' }}>{dpInfo.ztNum}</div>
                  </div>
                  <div style={{ width: '100%', display: 'flex', alignItems: 'center' }}>
                    <div>跌停家数</div>
                    <Progress percent={(dpInfo.dtNum / 100) * 100} strokeColor="green" showInfo={false} style={{ flex: 1, marginLeft: '10px' }} />
                    <div style={{ marginLeft: '10px' }}>{dpInfo.dtNum}</div>
                  </div>
                  <div style={{ width: '100%', display: 'flex', alignItems: 'center' }}>
                    <div>上涨家数</div>
                    <Progress percent={(dpInfo.szNum / 6000) * 100} strokeColor="red" showInfo={false} style={{ flex: 1, marginLeft: '10px' }} />
                    <div style={{ marginLeft: '10px' }}>{dpInfo.szNum}</div>
                  </div>
                  <div style={{ width: '100%', display: 'flex', alignItems: 'center' }}>
                    <div>下跌家数</div>
                    <Progress percent={(dpInfo.xdNum / 6000) * 100} strokeColor="green" showInfo={false} style={{ flex: 1, marginLeft: '10px' }} />
                    <div style={{ marginLeft: '10px' }}>{dpInfo.xdNum}</div>
                  </div>
                </div>
                <div style={{ flex: 1, display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
                  <Progress type="circle" percent={dpInfo.qd} strokeColor={getCircleColor(dpInfo.qd)} />
                </div>
              </div>
            </div>
          </Card>
          <Card title="竞价指数">
            <div style={{ height: '300px' }}>
              <ReactECharts option={getMarketEmotionOption()} style={{ height: '100%' }} />
            </div>
          </Card>
        </Col>
        <Col span={16}>
          <Card title="市场强度走势">
            <div style={{ height: '300px' }}>
              <ReactECharts option={getCombinedOption()} style={{ height: '100%' }} />
            </div>
          </Card>
          <Card title="竞价走势">
          <div style={{ height: '200px' }}>
            <ReactECharts option={getBidOption()} style={{ height: '100%' }} />
          </div>
          </Card>
        </Col>
      </Row>
      <Row>
        <Col span={24}>
          <Card title="大盘分时强度">
          <div style={{ height: '300px' }}>
            <ReactECharts option={getTraceOption()} style={{ height: '100%' }} />
          </div>
          </Card>
        </Col>
      </Row>
      <Row>
        <Col span={24}>
          <Card title="板块分时强度">
          <div style={{ height: '300px' }}>
          <Select style={{ width: 200 }}
              value={curBkCode}
              onChange={bkSelectChange}
              options={bkList}
            />
            <ReactECharts option={getBkTraceOption()} style={{ height: '100%' }} />
          </div>
          </Card>
        </Col>
      </Row>
      
    </div>
  );
};

export default Monitor;